﻿using OAS.Application.AttendanceApp.Services;
using OAS.Application.ReimburseApp.Dtos;
using OAS.Application.System.Dtos;
using OAS.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace OAS.Application.RequestApp.Services
{
    public class RequestService : Repository<Request>, IRequestService, ITransient
    {
        public async Task<List<Request>> GetAllRequest()
        {
            return await base.GetListAsync();
        }
        public async Task<object> GetRequestList(DtoQuery dto)
        {
            Expression<Func<Request, User, bool>> sqlWhere = Expressionable.Create<Request, User>() //创建表达式
                .AndIF(!string.IsNullOrEmpty(dto.UserName), (o, user) => o.UserName.Equals(dto.UserName))
                .AndIF(UserContext.CurrentUser.RoleName != "总经理" && UserContext.CurrentUser.RoleName != "主管" && !UserContext.IsAdmin, (o, user) => o.UserName == UserContext.CurrentUser.UserName)
                .AndIF(UserContext.CurrentUser.RoleName == "主管", (o, user) => user.Department_Id == UserContext.CurrentUser.Department_Id)
                .ToExpression();
            RefAsync<int> total = 0;
            var list = await base.AsQueryable()
                .LeftJoin<User>((o, user) => o.UserName == user.UserName)
                .Where(sqlWhere).ToPageListAsync(dto.PageIndex, dto.PageSize, total);
            return new { list, total };
        }
        public async Task AddRequest(Request request)
        {
            request.StartDate = request.StartDate == null ? null : TimeZoneInfo.ConvertTimeFromUtc((DateTime)request.StartDate, TimeZoneInfo.Local);
            request.EndDate = request.EndDate == null ? null : TimeZoneInfo.ConvertTimeFromUtc((DateTime)request.EndDate, TimeZoneInfo.Local);
            request.RequestTime = DateTime.Now;
            request.AuditStatus = 0;
            await base.InsertAsync(request);
        }
        public async Task UpdateRequest(Request request)
        {
            request.StartDate = request.StartDate == null ? null : TimeZoneInfo.ConvertTimeFromUtc((DateTime)request.StartDate, TimeZoneInfo.Local);
            request.EndDate = request.EndDate == null ? null : TimeZoneInfo.ConvertTimeFromUtc((DateTime)request.EndDate, TimeZoneInfo.Local);
            await base.UpdateAsync(request);
        }
        public async Task DeleteRequest(string[] ids)
        {
            await base.DeleteByIdsAsync(ids);
        }
        public async Task AuditRequest(DtoAudit dto)
        {
            await base.AsUpdateable().SetColumns(o => new Request { AuditStatus = dto.AuditStatus, Auditor = UserContext.UserName, AuditTime = DateTime.Now })
                   .Where(o => dto.Ids.Contains(o.Id.ToString())).ExecuteCommandAsync();
        }
    }
}
